<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VSelect v-model="form.supplier_name" placeholder="供应商" type="supplierName" allow-create style="min-width: 160px" multiple collapse-tags clearable filterable />
        <VSelect v-model="form.company_id" placeholder="公司主体" :options="options.company_id" multiple collapse-tags style="min-width: 210px" />
        <VSelect v-model="form.period_id" placeholder="结算方式" type="period" multiple collapse-tags style="min-width: 220px" />
        <VCascader v-model="form.department_name" placeholder="部门" type="department" multiple collapse-tags checkStrictly style="min-width: 160px" />
        <VSelect v-model="form.currency" placeholder="原币" :options="options.currency" multiple collapse-tags style="min-width: 160px" />
        <VGroup>
          <div class="v-group-item">统计月份</div>
          <el-date-picker v-model="form.dateRange.value" type="monthrange" value-format="YYYY-MM" range-separator="至" start-placeholder="开始月份" end-placeholder="结束月份"
            style="max-width: 300px" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VTotal ref="totalRef" url="/v1/finance/payable-balances/total" class="w-10/12" :options="[
          { title: '累计付款金额', key: 'payment_price' },
          { title: '累计运费', key: 'tracking_price' },
          { title: '累计优惠', key: 'discount_price' },
          { title: '累计折扣', key: 'preferential_price' },
          { title: '累计售后', key: 'after_sale_price' },
          { title: '累计退款', key: 'refund_price' },
          { title: '累计入库产品金额', key: 'inbound_price' },
          { title: '期末余额', key: 'end_balances' },
          { title: '期末余额CNY', key: 'end_balances_cny' },
          ]" :child="val => (val || []).map(d => `${d.currency}: ${d.price}`).join(' ')" />
        <VImport auth="/purchase/finance/payable/import" :tableRef="tableRef" importUrl="/v1/finance/payable-balances/import-adjust"
          downloadUrl="https://xc-pms.oss-cn-shenzhen.aliyuncs.com/template/调整金额导入模板.xlsx" class="ml-auto" @success="query" />
        <VExport auth="/purchase/finance/payable/export" mainKey="pb_id" name="payable-balances" :tableRef="tableRef" task />
      </template>
    </VTable>
    <Adjust ref="adjustRef" :options="options" @success="query" />
    <VLog ref="logRef" />
  </VPage>
</template>
  
<script setup lang="jsx">
import api from '../api'
import VTotal from '@/components/VTotal'
import VImport from '@/components/VImport'
import Adjust from './Adjust'
import { getOption } from '@/api/public'

const baseName = 'payable'
const tableRef = ref()
const logRef = ref()
const totalRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 单行操作
const adjustRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { pb_id } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    adjust: () => {
      const { pb_id, month } = row
      adjustRef?.value.open({ pb_id, month })
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, pb_id })
    },
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  rowConfig: { height: 100 },
  showHeaderOverflow: false,
  showOverflow: false,
  formConfig: {
    data: {
      dateRange: { type: 'month', value: [], range: true },
    }
  },
  columns: [
    { title: '月份', field: 'month', minWidth: 100 },
    {
      title: '公司主体', field: 'company_id_name', minWidth: 140, slots: {
        header: () => <div>公司主体</div>,
        default: ({ row }) => <VText value={row.company_id_name} line={3} />
      }
    },
    {
      minWidth: 140, slots: {
        header: () => <div>供应商信息</div>,
        default: ({ row }) => <div>
        <VText value={row.supplier_name} line={3} />
        <VText title='供应商ID' value={row.supplier_code} />
        </div>
      }
    },
    { title: '类型', field: 'payable_type_name', minWidth: 100 },
    {
      title: '结算方式', field: 'period_name', minWidth: 140, slots: {
        default: ({ row }) => <VText value={row.period_name} line={3} />
      }
    },
    {
      title: '部门', field: 'department_name', minWidth: 100, slots: {
        default: ({ row }) => <VText value={row.department_name} line={3} />
      }
    },
    { title: '原币', field: 'currency_name', minWidth: 100 },
    { title: '期初余额', field: 'start_balances', minWidth: 100 },
    { title: '调整金额', field: 'adjust_price', minWidth: 100 },
    { title: '累计付款金额', field: 'payment_price', minWidth: 100 },
    {
      minWidth: 150, slots: {
        header: () => <div>累计运费/累计优惠<br />累计折扣/累计售后</div>,
        default: ({ row }) => <div>
          <VText title='累计运费' value={row.tracking_price}></VText>
          <VText title='累计优惠' value={row.discount_price}></VText>
          <VText title='累计折扣' value={row.preferential_price}></VText>
          <VText title='累计售后' value={row.after_sale_price}></VText>
        </div>
      }
    },
    { title: '累计退款金额', field: 'refund_price', minWidth: 100 },
    { title: '累计运费退税金额', field: 'refund_tracking_price', minWidth: 100 },
    { title: '累计入库产品金额', field: 'inbound_price', minWidth: 100 },
    { title: '期末余（原币）', field: 'end_balances', minWidth: 100 },
    { title: '期末余额（CNY）', field: 'end_balances_cny', minWidth: 100 },
    {
      minWidth: 120, slots: {
        header: () => <div>备注</div>,
        default: ({ row }) => <VText value={row.remark} line={3} />
      }
    },
    {
      title: '操作', width: 80, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          return [<div class='nm flex flex-col gap-1 items-start'>
            <VButton auth="/purchase/finance/payable/adjust" link type="primary" onClick={() => handleRow('adjust', row)}>调整</VButton>
            <VButton auth="/purchase/finance/payable/log" link type="primary" onClick={() => handleRow('log', row)}>日志</VButton>
          </div>]
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        totalRef?.value.update({ ...form, ...page })
        return api.query({ ...form, ...page })
      }
    }
  }
})
</script>
  